<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
  },
}
</route>
<template>
  <view class="personal-center-page bg-main1 min-h-screen bg-gray-50 pb-20">
    <!-- #ifdef MP-WEIXIN -->
    <view class="pt-header" />
    <!-- #endif -->

    <view class="text-black p-6">
      <view class="flex items-center">
        <view class="flex items-center">
          <view class="relative">
            <image
              :src="userStore?.userInfo?.avatarImage"
              alt="User Avatar"
              class="w-16 h-16 rounded-full border-2 border-white object-cover"
              @click="navigateTo('/pages/mine/change')"
            />
          </view>

          <view class="ml-4">
            <view class="flex items-center">
              <view class="font-bold text-lg">{{ userStore?.userInfo?.nickName }}</view>
            </view>
            <view class="text-black text-sm">ID: {{ userStore?.userInfo?.uid }}</view>
          </view>
        </view>
      </view>

      <view class="flex justify-around mt-6 pt-4 mb-4 border-t border-white/20">
        <navigator url="/pages/mine/trans" class="text-center">
          <view class="text-black/80 text-xs mt-1">余额</view>
          <view class="font-bold text-lg">¥{{ userStore?.userInfo?.balanceQuota }}</view>
        </navigator>

        <navigator url="/pages/mine/trans" class="text-center">
          <view class="text-black/80 text-xs mt-1">积分</view>
          <view class="font-bold text-lg">0</view>
        </navigator>

        <navigator url="/pages/mine/trans" class="text-center">
          <view class="text-black/80 text-xs mt-1">优惠券</view>
          <view class="font-bold text-lg">0</view>
        </navigator>
      </view>
    </view>

    <view class="bg-white rounded-lg shadow-sm mx-4 -mt-4 mb-4 p-2">
      <view class="flex justify-between items-center mb-4">
        <view class="font-bold text-gray-800">我的订单</view>
        <view
          class="flex items-center text-sm text-gray-500"
          @click="navigateTo(`/pages/order/index`)"
        >
          查看全部
          <i class="iconfont icon-xiangyou1 w-4 text-4 ml-1"></i>
        </view>
      </view>

      <view class="grid grid-cols-4 gap-2">
        <view
          v-for="(status, index) in orderStatuses"
          :key="index"
          class="flex flex-col items-center"
          @click="navigateTo(status.link)"
        >
          <view class="relative">
            <view class="w-12 h-12 rounded-full bg-orange-50 flex items-center justify-center mb-1">
              <i v-if="index == 0" class="iconfont icon-duozhongzhifu text-7 text-center w-12"></i>
              <i v-if="index == 1" class="iconfont icon-yishouchu text-7 text-center w-12"></i>
              <i v-if="index == 2" class="iconfont icon-liuyan text-7 text-center w-12"></i>
              <i v-if="index == 3" class="iconfont icon-chexiao text-7 text-center w-12"></i>
            </view>
            <view
              v-if="status.count > 0"
              class="absolute -top-1 -right-1 bg-red-500 text-white text-xs min-w-[18px] h-[18px] rounded-full flex items-center justify-center px-1"
            >
              {{ status.count > 99 ? '99+' : status.count }}
            </view>
          </view>
          <text class="text-xs text-gray-700">{{ status.label }}</text>
        </view>
      </view>
    </view>

    <view class="bg-white rounded-lg shadow-sm mx-4 mb-4 p-2">
      <view class="font-bold text-gray-800 mb-4">我的服务</view>

      <view class="grid grid-cols-4 gap-4">
        <view class="flex flex-col items-center" @click="navigateTo('/pages/mine/invite')">
          <view class="w-12 h-12 rounded-full bg-orange-50 flex items-center justify-center mb-1">
            <i class="iconfont icon-yaoqing text-7 text-center w-12"></i>
          </view>
          <text class="text-xs text-gray-700 text-center">邀请好友</text>
        </view>

        <view
          v-if="!store && shenhe == 0"
          class="flex flex-col items-center"
          @click="navigateTo('/pages/join/index')"
        >
          <view class="w-12 h-12 rounded-full bg-orange-50 flex items-center justify-center mb-1">
            <i class="iconfont icon-shangjiaruzhu text-7 text-center w-12"></i>
          </view>
          <text class="text-xs text-gray-700 text-center">商家入驻</text>
        </view>

        <view
          v-if="store && shenhe == 0"
          class="flex flex-col items-center"
          @click="navigateTo('/pages/store/center?id=' + store.id)"
        >
          <view class="w-12 h-12 rounded-full bg-orange-50 flex items-center justify-center mb-1">
            <i class="iconfont icon-dianpu text-7 text-center w-12"></i>
          </view>
          <text class="text-xs text-gray-700 text-center">商家中心</text>
        </view>

        <view class="flex flex-col items-center" @click="navigateTo('/pages/turntable/index')">
          <view class="w-12 h-12 rounded-full bg-orange-50 flex items-center justify-center mb-1">
            <i class="iconfont icon-dazhuanpan text-7 text-center w-12"></i>
          </view>
          <text class="text-xs text-gray-700 text-center">大转盘</text>
        </view>

        <view class="flex flex-col items-center" @click="openScan" v-if="store != null">
          <view class="w-12 h-12 rounded-full bg-orange-50 flex items-center justify-center mb-1">
            <i class="iconfont icon-saoma text-7 text-center w-12"></i>
          </view>
          <text class="text-xs text-gray-700 text-center">扫码核销</text>
        </view>

        <view class="flex flex-col items-center" @click="openCommunity">
          <view class="w-12 h-12 rounded-full bg-orange-50 flex items-center justify-center mb-1">
            <i class="iconfont icon-tequanzhuanshu text-7 text-center w-12"></i>
          </view>
          <text class="text-xs text-gray-700 text-center">社区</text>
        </view>

        <view
          class="flex flex-col items-center"
          v-if="shenhe == 0"
          @click="navigateTo('/pages/collect/index')"
        >
          <view class="w-12 h-12 rounded-full bg-orange-50 flex items-center justify-center mb-1">
            <i class="iconfont icon-dianpufill text-7 text-center w-12"></i>
          </view>
          <text class="text-xs text-gray-700 text-center">收藏店铺</text>
        </view>
      </view>
    </view>
    <!-- 
    <view class="bg-white rounded-lg shadow-sm mx-4 mb-4">
      <view
        v-for="(link, index) in footerLinks"
        :key="index"
        class="flex items-center justify-between p-2 border-b border-gray-100 last:border-0"
        @click="navigateTo(link.link)"
      >
        <view class="flex items-center">
          <i v-if="index == 0" class="iconfont icon-zantong w-4 text-4 mr-1"></i>
          <i v-if="index == 1" class="iconfont icon-fankui w-4 text-4 mr-1"></i>
          <i v-if="index == 2" class="iconfont icon-dianpu w-4 text-4 mr-1"></i>
          <text class="text-gray-700">{{ link.label }}</text>
        </view>
        <i class="iconfont icon-xiangyou1 w-4 text-4"></i>
      </view>
    </view> -->

    <view class="mx-4 mt-6">
      <view
        class="w-full py-3 bg-[#ff6a33] text-center text-white font-medium border border-orange-500 rounded-lg"
        @click="logout"
      >
        退出登录
      </view>
    </view>

    <!-- 产品信息弹窗 -->
    <wd-popup v-model="scanShow" closeable>
      <!-- 订单信息 -->
      <view
        class="bg-white rounded-lg w-84 min-h-64 p-4 rounded shadow-sm overflow-hidden"
        v-if="order"
      >
        <view class="p-3 border-b border-gray-100 flex justify-between items-center">
          <view class="flex items-center">
            <text class="text-xs text-gray-500">订单编号：{{ order.orderId }}</text>
            <text
              v-if="order.isUrgent"
              class="ml-2 px-1.5 py-0.5 bg-red-100 text-red-500 text-xs rounded"
            >
              加急
            </text>
          </view>
          <text
            class="text-sm font-medium"
            :class="{
              'text-black-500': order.status === 0,
              'text-blue-500': order.status === 1,
              'text-green-500': order.status === 3,
              'text-purple-500': order.status === 5,
            }"
          >
            {{ parseStatus(order.status) }}
          </text>
        </view>

        <view class="p-3 flex">
          <!-- Product Image -->
          <view class="relative">
            <image
              :src="order.productImage"
              :alt="order.productName"
              class="w-20 h-20 object-cover rounded-md"
            />
            <view
              class="absolute -bottom-1 -right-1 bg-gray-800/70 text-white text-xs px-1.5 py-0.5 rounded-full"
            >
              x{{ order.totalNum }}
            </view>
          </view>

          <!-- Order Info -->
          <view class="ml-3 flex-1">
            <view class="font-medium text-gray-800 line-clamp-2">{{ order.productName }}</view>

            <view class="mt-1 flex justify-between items-baseline">
              <view>
                <text class="text-sm text-gray-500">¥{{ order.totalPrice }}</text>
                <text class="text-xs text-gray-400 ml-1">x{{ order.totalNum }}</text>
              </view>
              <view class="text-sm font-medium">
                <text class="text-gray-500">合计：</text>
                <text class="text-black-500">¥{{ order.totalPrice }}</text>
              </view>
            </view>

            <view class="mt-2 flex flex-wrap text-xs text-gray-500">
              <text class="mr-3" v-if="order.channel == 0">支付方式：微信支付</text>
              <text class="mr-3" v-if="order.channel == 1">支付方式：支付宝支付</text>
              <text>下单时间：{{ order.createTime }}</text>
            </view>

            <view v-if="order.verificationTime" class="mt-1 text-xs text-gray-500">
              核销时间：{{ order.verificationTime }}
            </view>
          </view>
        </view>

        <!-- 核销按钮 -->
        <view
          class="w-full py-3 bg-[#ff6a33] text-center text-white font-medium border border-orange-500 rounded-lg"
          @click="submit"
        >
          核销
        </view>
      </view>
    </wd-popup>

    <!-- 弹窗 -->
    <wd-popup v-model="qrCodeShow">
      <view v-if="selectCommunity" class="p-2 flex flex-col justify-start items-center">
        <text class="mb-2">社区名称：{{ selectCommunity?.communityName }}</text>
        <text class="mb-2">群聊二维码</text>
        <image :src="selectCommunity?.qrCode" mode="scaleToFill" class="w-75 h-75" />
      </view>
    </wd-popup>
  </view>
</template>

<script setup>
import { http } from '@/utils/http'
import { useUserStore } from '@/store'

const userStore = useUserStore()
const store = ref(null)

const getUserInfo = async () => {
  let res = await http.get('/api/user/my')
  if (res.code == 200) {
    userStore.setUserInfo(res.data)
  }

  let resp = await http.get('/api/home/queryOrderStatusCount')
  if (res.code == 200) {
    orderStatuses.value[0].count = resp.data?.obligation || 0
    orderStatuses.value[1].count = resp.data?.pendingVerification || 0
    orderStatuses.value[2].count = resp.data?.evaluate || 0
    orderStatuses.value[3].count = resp.data?.afterSales || 0
  }

  if (userStore && userStore.userInfo && userStore.userInfo.grade == 1) {
    let resp1 = await http.get('/api/store/query')
    if (resp1.code == 200) {
      store.value = resp1.data.store
    }
  }
}

const shenhe = ref(1)

const getConfig = async () => {
  let res2 = await http.get('/api/config/list', {
    code: 'shenhe',
  })
  if (res2.code == 200) {
    shenhe.value = Number(res2.data.list[0].value)
  }
}

onShow(() => {
  getUserInfo()
  getConfig()
})

const parseStatus = (status) => {
  if (status == 0) {
    return '待付款'
  } else if (status == 1) {
    return '待核销'
  } else if (status == 3) {
    return '待评价'
  } else if (status == 4) {
    return '已完成'
  } else if (status == 5) {
    return '售后/退款'
  }
}

const orderStatuses = ref([
  {
    label: '待付款',
    value: 'to-pay',
    icon: 'CreditCard',
    count: 2,
    link: '/pages/order/index?status=0',
  },
  {
    label: '待核销',
    value: 'to-deliver',
    icon: 'Package',
    count: 0,
    link: '/pages/order/index?status=1',
  },
  {
    label: '待评价',
    value: 'to-review',
    icon: 'MessageSquare',
    count: 3,
    link: '/pages/order/index?status=3',
  },
  {
    label: '售后/退款',
    value: 'after-sale',
    icon: 'Star',
    count: 0,
    link: '/pages/order/index?status=5',
  },
])

const footerLinks = [
  { label: '帮助中心', icon: 'HelpCircle', link: '/help-center' },
  { label: '关于我们', icon: 'InfoIcon', link: '/about-us' },
]

// Navigation function
const navigateTo = (url) => {
  uni.navigateTo({ url })
}

// Logout function
const logout = () => {
  uni.clearStorage()
  uni.reLaunch({ url: '/pages/login/index' })
}

const scanShow = ref(false)

const order = ref(null)

const qrCodeShow = ref(false)
const selectCommunity = ref(null)

const openCommunity = async () => {
  uni.getLocation({
    type: 'gcj02',
    success: async (res) => {
      // 发送定位

      let resp = await http({
        url: '/api/community/list',
        method: 'GET',
        params: {
          longitude: res.longitude,
          dimension: res.latitude,
        },
      })

      if (resp.code == 200) {
        if (resp.data.list.length > 0) {
          let community = resp.data.list[0]
          console.log(
            '%c [ community ]-365',
            'font-size:13px; background:pink; color:#bf2c9f;',
            community,
          )
          selectCommunity.value = community
          qrCodeShow.value = true
        }
      }
    },
  })
}

const openScan = () => {
  // 获取订单信息
  uni.scanCode({
    onlyFromCamera: true,
    success: async (res) => {
      // 调用查询订单信息接口
      let resp = await http.get('/api/home/queryByOrderId', { orderId: res.result })
      if (resp.code == 200) {
        order.value = resp.data
        scanShow.value = true
      }
    },
  })
}

const submit = async () => {
  uni.showModal({
    title: '提示',
    content: '是否确认核销',
    showCancel: true,
    success: async ({ confirm, cancel }) => {
      if (confirm) {
        let resp = await http.get('/api/home/writeOrder', {
          verificationCode: order.value.verificationCode,
          storeId: store.value.id,
        })

        if (resp.code == 200) {
          scanShow.value = false

          uni.showToast({
            title: resp.msg,
            icon: 'none',
            mask: false,
          })
        }
      }
    },
  })
}
</script>

<style scoped>
.line-clamp-1 {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
